package cn.johnyu.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 用于检查session中是否有用户信息，如果有，则将用户信息放入SecurityContextHolder中,并在FilterChain注册它的实例
 */
@Component
public class CookieCheckFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user==null){//如果没有用户信息，则放行给"鉴权过滤器"（FilterSecurityInterceptor），结果为403
            filterChain.doFilter(request,response);
            return;
        }
        //已经登录,将认证信息(Authentication)放入SecurityContextHolder中(其中包括是否认证成功，用户信息，权限信息)
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),null,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        放行给"鉴权过滤器"（FilterSecurityInterceptor），在那里根据自定义的鉴权逻辑进行鉴权
        filterChain.doFilter(request,response);
    }
}
